<!--
  智慧社区管理系统 - 催缴弹窗组件
  @author Wu.Liang
  @date 2024-12-21
-->
<template>
  <el-dialog
    v-model="dialogVisible"
    title="发送催缴提醒"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <div v-if="feeData" class="reminder-content">
      <!-- 费用信息 -->
      <el-card class="fee-info-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>费用信息</span>
          </div>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="账单号">{{ feeData.feeNo }}</el-descriptions-item>
          <el-descriptions-item label="费用类型">{{ getFeeTypeText(getFeeType(feeData)) }}</el-descriptions-item>
          <el-descriptions-item label="业主">{{ feeData.householdName }}</el-descriptions-item>
          <el-descriptions-item label="房户">{{ feeData.communityName }} - {{ feeData.buildingName }} - {{ feeData.roomNumber }}</el-descriptions-item>
          <el-descriptions-item label="未缴金额">
            <span class="amount unpaid">¥{{ feeData.unpaidAmount?.toFixed(2) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="到期日期">{{ feeData.dueDate }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 催缴表单 -->
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="reminder-form"
      >
        <el-form-item label="催缴方式" prop="remindType">
          <el-radio-group v-model="form.remindType">
            <el-radio value="SMS">
              <el-icon><Message /></el-icon>
              短信提醒
            </el-radio>
            <el-radio value="EMAIL">
              <el-icon><Message /></el-icon>
              邮件提醒
            </el-radio>
            <el-radio value="APP_PUSH">
              <el-icon><Bell /></el-icon>
              应用推送
            </el-radio>
            <el-radio value="PHONE">
              <el-icon><Phone /></el-icon>
              电话提醒
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="催缴模板">
          <el-select
            v-model="selectedTemplate"
            placeholder="请选择催缴模板"
            style="width: 100%"
            @change="handleTemplateChange"
          >
            <el-option
              v-for="template in reminderTemplates"
              :key="template.id"
              :label="template.name"
              :value="template.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="催缴内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="6"
            placeholder="请输入催缴内容"
            show-word-limit
            :maxlength="500"
          />
        </el-form-item>

        <el-form-item label="发送时间">
          <el-radio-group v-model="form.sendTime">
            <el-radio value="NOW">立即发送</el-radio>
            <el-radio value="SCHEDULED">定时发送</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          v-if="form.sendTime === 'SCHEDULED'"
          label="发送时间"
          prop="scheduledTime"
        >
          <el-date-picker
            v-model="form.scheduledTime"
            type="datetime"
            placeholder="请选择发送时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <!-- 催缴预览 -->
      <el-card class="preview-card" shadow="never">
        <template #header>
          <div class="card-header">
            <span>催缴预览</span>
          </div>
        </template>
        <div class="preview-content">
          <div class="preview-item">
            <span class="label">发送对象：</span>
            <span>{{ feeData.householdName }} ({{ feeData.roomNumber }})</span>
          </div>
          <div class="preview-item">
            <span class="label">催缴方式：</span>
            <span>{{ getRemindTypeText(form.remindType) }}</span>
          </div>
          <div class="preview-item">
            <span class="label">发送时间：</span>
            <span>{{ getSendTimeText() }}</span>
          </div>
          <div class="preview-item">
            <span class="label">催缴内容：</span>
            <div class="content-preview">{{ form.content || '暂无内容' }}</div>
          </div>
        </div>
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button
          type="primary"
          :loading="loading"
          @click="handleSubmit"
        >
          确认发送
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { Message, Bell, Phone } from '@element-plus/icons-vue'
import type { PropertyFee, SanitationFee, GasFee, UtilityFee, ReminderParams } from '../types/property'
import { reminderApi } from '@/api/property'

// Props
interface Props {
  modelValue: boolean
  feeData: PropertyFee | SanitationFee | GasFee | UtilityFee | null
  loading?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  loading: false
})

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'confirm': [data: ReminderParams]
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const reminderTemplates = ref<Array<{
  id: number
  name: string
  content: string
  remindType: string
}>>([])
const selectedTemplate = ref<number>()

// 表单数据
const form = reactive<ReminderParams & {
  sendTime: 'NOW' | 'SCHEDULED'
  scheduledTime?: string
}>({
  billId: 0,
  remindType: 'SMS',
  content: '',
  sendTime: 'NOW'
})

// 表单验证规则
const rules: FormRules = {
  remindType: [
    { required: true, message: '请选择催缴方式', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入催缴内容', trigger: 'blur' },
    { min: 10, message: '催缴内容至少10个字符', trigger: 'blur' }
  ],
  scheduledTime: [
    { required: true, message: '请选择发送时间', trigger: 'change' }
  ]
}

// 计算属性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 监听器
watch(() => props.feeData, (newVal) => {
  if (newVal) {
    form.billId = newVal.id
    generateDefaultContent()
  }
}, { immediate: true })

// 生命周期
onMounted(() => {
  loadReminderTemplates()
})

// 工具函数
const getFeeType = (fee: PropertyFee | SanitationFee | GasFee | UtilityFee): number | string => {
  if ('feeType' in fee) {
    return fee.feeType
  }
  if ('utilityType' in fee) {
    return fee.utilityType
  }
  return 'UNKNOWN'
}

const FEE_TYPE_TEXT_MAP: Record<number | string, string> = {
  0: '物业费',
  1: '卫生费',
  2: '水费',
  3: '电费',
  4: '燃气费',
  PROPERTY_FEE: '物业费',
  SANITATION_FEE: '卫生费',
  WATER_FEE: '水费',
  ELECTRICITY_FEE: '电费',
  GAS_FEE: '燃气费',
  WATER: '水费',
  ELECTRICITY: '电费'
}

const getFeeTypeText = (feeType: number | string) => {
  return FEE_TYPE_TEXT_MAP[feeType] || feeType
}

const getRemindTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    'SMS': '短信提醒',
    'EMAIL': '邮件提醒',
    'APP_PUSH': '应用推送',
    'PHONE': '电话提醒'
  }
  return typeMap[type] || type
}

const getSendTimeText = () => {
  if (form.sendTime === 'NOW') {
    return '立即发送'
  } else if (form.scheduledTime) {
    return form.scheduledTime
  }
  return '未设置'
}

// 加载催缴模板
const loadReminderTemplates = async () => {
  try {
    const response = await reminderApi.getReminderTemplates()
    if (response.success) {
      reminderTemplates.value = response.data
    }
  } catch (error) {
    console.error('加载催缴模板失败:', error)
  }
}

// 生成默认催缴内容
const generateDefaultContent = () => {
  if (!props.feeData) return
  
  const feeTypeText = getFeeTypeText(getFeeType(props.feeData))
  const defaultContent = `尊敬的${props.feeData.householdName}业主，您的${feeTypeText}账单（${props.feeData.feeNo}）尚未缴纳，未缴金额为¥${props.feeData.unpaidAmount?.toFixed(2)}，到期日期为${props.feeData.dueDate}。请及时缴纳，以免影响您的正常使用。如有疑问，请联系物业服务中心。`
  
  form.content = defaultContent
}

// 模板变更处理
const handleTemplateChange = (templateId: number) => {
  const template = reminderTemplates.value.find(t => t.id === templateId)
  if (template) {
    form.content = template.content
    form.remindType = template.remindType as any
  }
}

// 事件处理
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    
    const submitData: ReminderParams = {
      billId: form.billId,
      remindType: form.remindType,
      content: form.content
    }

    emit('confirm', submitData)
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

const handleCancel = () => {
  dialogVisible.value = false
  resetForm()
}

const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(form, {
    billId: 0,
    remindType: 'SMS',
    content: '',
    sendTime: 'NOW',
    scheduledTime: undefined
  })
  selectedTemplate.value = undefined
}
</script>

<style scoped>
.reminder-content {
  max-height: 600px;
  overflow-y: auto;
}

.fee-info-card,
.preview-card {
  margin-bottom: 20px;
}

.card-header {
  font-weight: 600;
  color: #303133;
}

.amount.unpaid {
  color: #f56c6c;
  font-weight: 600;
}

.reminder-form {
  margin-bottom: 20px;
}

.preview-content {
  padding: 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.preview-item {
  margin-bottom: 12px;
  line-height: 1.6;
}

.preview-item:last-child {
  margin-bottom: 0;
}

.preview-item .label {
  font-weight: 600;
  color: #303133;
  margin-right: 8px;
}

.content-preview {
  margin-top: 8px;
  padding: 12px;
  background-color: #ffffff;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  color: #606266;
  line-height: 1.6;
  white-space: pre-wrap;
}

.dialog-footer {
  text-align: right;
}
</style> 